/*******************************************************************************
 * Copyright (c) 2022, 2022
 ******************************************************************************/
package com.alex.demo.rabbitmq.controller;

import java.util.Date;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alex.demo.rabbitmq.config.DelayedQueueConfig;
import com.alex.demo.rabbitmq.config.TTLQueueConfig;

import lombok.extern.slf4j.Slf4j;

/**
 * @Version 1.0
 * @Author Alex
 * @Created Dec 2022/9/26 14:04
 * @Description
 *              <p>
 *              发送延迟消息
 */
@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMsgController {

	@Autowired
	private RabbitTemplate rabbitTemplate;

	@GetMapping("/sendMsg/{message}")
	public void sendMsg(@PathVariable String message) {
		log.info("当前时间：{}，发送一条消息给两个TTL队列：{}", new Date().toString(), message);
		rabbitTemplate.convertAndSend("X", "XA", "消息来自tll为10s的队列：" + message);
		rabbitTemplate.convertAndSend("X", "XB", "消息来自tll为40s的队列：" + message);
	}

	@GetMapping("/sendMsgWithTTL/{message}/{ttlTime}")
	public void sendMsgWithTTLTime(@PathVariable String message, @PathVariable String ttlTime) {
		log.info("当前时间：{}，发送一条时长{}毫秒TTL消息给队列QC：{}", new Date().toString(), ttlTime, message);
		rabbitTemplate.convertAndSend(TTLQueueConfig.X_EXCHANGE, "XC", message, msg -> {
			// 发送消息的时候，设置ttl时间
			msg.getMessageProperties().setExpiration(ttlTime);
			return msg;
		});
	}

	@GetMapping("/sendDelayMsg/{message}/{delayTime}")
	public void sendMsgWithDelayTime(@PathVariable String message, @PathVariable Integer delayTime) {
		log.info("当前时间：{}，发送一条时长{}毫秒信息给延迟给队列delayed.queue：{}", new Date().toString(), delayTime, message);
		rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE_NAME, DelayedQueueConfig.DELAYED_ROUTING_KEY, message, msg -> {
			// 发送消息的时候，指定延迟时长 单位：ms
			msg.getMessageProperties().setDelay(delayTime);
			return msg;
		});
	}

}
